﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using WXYW.BLL;
using WXYW.DAL;
using System.Web.Configuration;

namespace WXYW
{
    public partial class ConfirmProduct1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindProduct();
            }
            
        }

        private void BindProduct()
        {
            try
            {
                ApplicationService service = new ApplicationService();
                ApplicationForm application = service.GetApplicationFormDetailByID(long.Parse(Request.QueryString[Constants.QUERYSTR_APPLICATION_ID]));
                productGridView.DataSource = application.ApplicationProduct.OrderBy(p => p.ApplicationProductID);
                productGridView.DataBind();
                applyCompanyNameTxtBox.Text = application.User.FullName;
                mailAddressTxtBox.Text = application.User.UserAddress;
                applierEmailTxtBox.Text = application.User.UserEmail;
                applierFaxTxtBox.Text = application.User.UserFax;
                rmaLabel.Text = application.ApplicationCode;
                runningNumberLabel.Text = application.RunningNumber;
                statusLabel.Text = application.Status;
                applierMobilePhoneTxtBox.Text = application.User.UserMobilePhone;
                applierNameTxtBox.Text = application.User.ContactPerson;
                applierPhoneTxtBox.Text = application.User.UserPhone;
                ProviderNameTxtBox.Text = application.ProviderName;

                if (application.AgentID != null)
                {
                    UserService userservice = new UserService();
                    User agent = userservice.GetUserByID(application.AgentID.Value);
                    agentpersonLabel.Text = agent.ContactPerson;
                    agentpersonPhoneLabel.Text = agent.UserMobilePhone;
                }

                if (!application.ApplicationPicture.IsLoaded)
                {
                    application.ApplicationPicture.Load();
                }
                List<ApplicationPicture> list = application.ApplicationPicture.Where(p => p.Type == (int)PictureType.ConfirmProduct).ToList();
                Table table = new Table();
                table.Rows.Add(new TableRow());
                table.Rows.Add(new TableRow());
                foreach (ApplicationPicture picture in list)
                {
                    TableCell celllImage = new TableCell();
                    Image imageControl = new Image();
                    imageControl.Height = 100;
                    imageControl.ImageUrl = "Picture/" + picture.PictureNameOnServer;
                    imageControl.Attributes.Add("OnClick", "window.open('ImageDetail.aspx?Name=" + picture.PictureNameOnServer + "')");
                    celllImage.Controls.Add(imageControl);
                    table.Rows[0].Cells.Add(celllImage);

                    TableCell cellName = new TableCell();
                    Label label = new Label();
                    label.Text = picture.PictureName;
                    cellName.Controls.Add(label);
                    table.Rows[1].Cells.Add(cellName);
                }
                picturePanel.Controls.Add(table);

                receiverLbl.Text = application.User.UserEmail;
                contactLbl.Text = application.User.ContactPerson;
                mobilePhoneLbl.Text = application.User.UserMobilePhone;
                SMSTxtBox.Text = string.Format("神州数码网络客服中心提示 尊敬的{0}您好，您送修的{1}台设备已收到，我们会尽快安排维修，请保留您的RMA NO.{2}，以便查询，神州数码客服中心 01058859855",
                        application.User.ContactPerson, application.ApplicationProduct.Count, application.ApplicationCode);
            }
            catch (Exception ex)
            {
                LogUtility.LogUtilityIntance.LogException(ex, "ConfirmProduct1::BindProduct");
                throw ex;
            }
        }

        protected void productGridView_RowEditing(object sender, GridViewEditEventArgs e)
        {
            try
            {
                productGridView.EditIndex = e.NewEditIndex;
                BindProduct();
                ApplicationProductService service = new ApplicationProductService();
                ApplicationProduct product = service.GetApplicationProductByID(long.Parse(productGridView.DataKeys[e.NewEditIndex].Value.ToString()));
                //
                DropDownList typeDDL = (DropDownList)productGridView.Rows[e.NewEditIndex].FindControl("typeDropDownList");
                typeDDL.DataSource = service.GetAllProductType();
                typeDDL.DataTextField = "ProductTypeName";
                typeDDL.DataValueField = "ProductTypeID";
                typeDDL.DataBind();
                typeDDL.SelectedValue = product.ProductType.ProductTypeID.ToString();
                //
                DropDownList repairTypeDDL = (DropDownList)productGridView.Rows[e.NewEditIndex].FindControl("repairTypeDropDownList");
                repairTypeDDL.Text = product.ProductRepairType;

                DropDownList problemTypeDDL = (DropDownList)productGridView.Rows[e.NewEditIndex].FindControl("problemTypeDropDownList");
                ProblemTypeService problemtypeservice = new ProblemTypeService();
                problemTypeDDL.DataSource = problemtypeservice.GetAllProblemType();
                problemTypeDDL.DataTextField = "Name";
                problemTypeDDL.DataValueField = "ID";
                problemTypeDDL.DataBind();
                if (!product.ProblemTypeReference.IsLoaded)
                {
                    product.ProblemTypeReference.Load();
                }
                problemTypeDDL.SelectedValue = product.ProblemType.ID.ToString();

                ProductClassService classService = new ProductClassService();
                DropDownList versionDDL = ((DropDownList)productGridView.Rows[e.NewEditIndex].FindControl("VersionNumberDDL"));
                versionDDL.DataSource = classService.GetVersionsWithSelectOne();
                versionDDL.DataTextField = "Name";
                versionDDL.DataValueField = "Name";
                versionDDL.SelectedValue = product.ProductVersionNumber;
                versionDDL.DataBind();
            }
            catch (Exception ex)
            {
                LogUtility.LogUtilityIntance.LogException(ex, "ConfirmProduct1::productGridView_RowEditing");
                throw ex;
            }
        }

        protected void productGridView_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            try
            {
                long productID = long.Parse(productGridView.DataKeys[e.RowIndex].Value.ToString());
                int productTypeID = Convert.ToInt32(((DropDownList)productGridView.Rows[e.RowIndex].FindControl("typeDropDownList")).SelectedValue);
                int amount = Convert.ToInt32(((TextBox)productGridView.Rows[e.RowIndex].FindControl("AmountTextBox")).Text);
                string productSerialNumber = ((TextBox)productGridView.Rows[e.RowIndex].FindControl("SNTxtBox")).Text;
                string problemDiscription = ((TextBox)productGridView.Rows[e.RowIndex].FindControl("ProblemDescriptionTxtBox")).Text;
                string productAppearance = ((TextBox)productGridView.Rows[e.RowIndex].FindControl("AppearanceTxtBox")).Text;
                string remark = ((TextBox)productGridView.Rows[e.RowIndex].FindControl("CommentTxtBox")).Text;
                string repairType = ((DropDownList)productGridView.Rows[e.RowIndex].FindControl("repairTypeDropDownList")).Text;
                int problemTypeID = Convert.ToInt32(((DropDownList)productGridView.Rows[e.RowIndex].FindControl("problemTypeDropDownList")).SelectedValue);
                string versionNumber = ((DropDownList)productGridView.Rows[e.RowIndex].FindControl("VersionNumberDDL")).Text;

                ApplicationProductService service = new ApplicationProductService();
                service.UpdateApplicationProduct(productID, productTypeID, amount, productSerialNumber,
                    problemDiscription, productAppearance, remark, repairType, problemTypeID, versionNumber);

                productGridView.EditIndex = -1;
                BindProduct();
            }
            catch (Exception ex)
            {
                LogUtility.LogUtilityIntance.LogException(ex, "ConfirmProduct1::productGridView_RowUpdating");
                throw ex;
            }
        }

        protected void productGridView_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            productGridView.EditIndex = -1;
            BindProduct();
        }

        protected void backLinkButton_Click(object sender, EventArgs e)
        {
            Response.Redirect("ListNeedConfirmProduct.aspx");
        }

        protected void okLinkButton_Click(object sender, EventArgs e)
        {
            try
            {
                ApplicationService service = new ApplicationService();
                ApplicationForm appForm = service.ConfirmReceivedProduct(long.Parse(Request.QueryString[Constants.QUERYSTR_APPLICATION_ID]));
                if (!appForm.ServiceStationReference.IsLoaded)
                {
                    appForm.ServiceStationReference.Load();
                }
                if (!appForm.ApplicationProduct.IsLoaded)
                {
                    appForm.ApplicationProduct.Load();
                }
                string products = string.Empty;
                foreach (ApplicationProduct product in appForm.ApplicationProduct)
                {
                    if (!product.ProductTypeReference.IsLoaded)
                    {
                        product.ProductTypeReference.Load();
                    }
                    if (!string.IsNullOrEmpty(products))
                    {
                        products = product.ProductType.ProductTypeName + "," + product.ProductSerialNumber;
                    }
                    else
                    {
                        products += product.ProductType.ProductTypeName + "," + product.ProductSerialNumber;
                    }
                }
                // send email
                if (!appForm.UserReference.IsLoaded)
                {
                    appForm.UserReference.Load();
                }
                string body = string.Format(WebConfigurationManager.AppSettings["ConfirmProduct"], appForm.User.UserName, appForm.ApplicationCode);
                // email to client
                EmailService.SendEmail(appForm.User.UserEmail, "货物已验收", body);
                // 发送短信
                //SMSService.SendSMS(string.Format("尊敬的{0}您好，您送修的{1}台设备已收到，我们会尽快安排维修，请保留您的RMA NO.{2}，以便查询，神州数码客服中心 01058859855",
                //    appForm.User.ContactPerson, appForm.ApplicationProduct.Count, appForm.ApplicationCode), 
                //    appForm.User.UserMobilePhone);
                
                // email to assignee
                RoleService roleService = new RoleService();
                List<User> userList = roleService.GetUserHasPermission(5);
                string assBody = string.Format(WebConfigurationManager.AppSettings["NeedDistributeProduct"], appForm.ApplicationCode, appForm.ServiceStation.Name, products);

                foreach (User user in userList)
                {
                    EmailService.SendEmail(user.UserEmail, "货物已验收", assBody);
                }
               
                

                ClientScript.RegisterStartupScript(this.GetType(), "Tip", "alert('您已成功确认了单号为" + appForm.ApplicationCode + "的送修货物，请及时与客户确认维修事宜！');", true);
                Response.Redirect("ListNeedConfirmProduct.aspx");
            }
            catch (Exception ex)
            {
                LogUtility.LogUtilityIntance.LogException(ex, "收获确认按钮");
                MsgLbl.Text = string.Format("系统错误:{0}", ex.Message);
                throw ex;
            }
        }

        protected void uploadButton_Click(object sender, EventArgs e)
        {
            try
            {
                string fileType = string.Empty;
                string fileName = string.Empty;
                string fileNameOnServer = string.Empty;
                if (FileUpload1.HasFile)
                {
                    fileType = FileUpload1.FileName.Substring(FileUpload1.FileName.LastIndexOf("."));
                    fileName = FileUpload1.FileName;
                    fileNameOnServer = Guid.NewGuid() + fileType;
                    FileUpload1.SaveAs(Server.MapPath("Picture/" + fileNameOnServer));
                }
                ApplicationService service = new ApplicationService();
                ApplicationForm form = service.GetApplicationFormByID(long.Parse(Request.QueryString[Constants.QUERYSTR_APPLICATION_ID]));
                ApplicationPicture picture = new ApplicationPicture
                {
                    PictureName = fileName,
                    PictureNameOnServer = fileNameOnServer,
                    Type = (int)PictureType.ConfirmProduct,
                    UploadPerson = ContextService.CurrentAccount.UserID
                };
                form.ApplicationPicture.Add(picture);
                service.UpdateApplication(form);
            }
            catch (Exception ex)
            {
                LogUtility.LogUtilityIntance.LogException(ex, "ConfirmProduct1::uploadButton_Click");
                throw ex;
            }
            BindProduct();
        }

        protected void productGridView_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.DataItem != null)
            {
                e.Row.Attributes.Add("onmouseover", "c=this.style.backgroundColor;this.style.backgroundColor='#FFFF99'");
                e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=c");
                ((Label)e.Row.FindControl("IDLbl")).Text = (e.Row.RowIndex + 1).ToString();
            }
        }

        protected void sendSMSLnkBtn_Click(object sender, EventArgs e)
        {
            try
            {
                string retCode = SMSService.SendSMS(mobilePhoneLbl.Text, SMSTxtBox.Text);
                if (retCode == "0")
                {
                    Response.Write(string.Format("<script language='JavaScript'> alert( '短信通知已经发送给客户！');location.href= '{0}?{1}={2}' </script> ", "ConfirmProduct.aspx", Constants.QUERYSTR_APPLICATION_ID, Request.QueryString[Constants.QUERYSTR_APPLICATION_ID]));
                }
            }
            catch (Exception ex)
            {
                LogUtility.LogUtilityIntance.LogException(ex, "ConfirmProduct1::sendSMSLnkBtn_Click");
                MsgLbl.Text = "短信发送失败，请重新发送。";
            }
        }
    }
}
